﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WLFramework.Validation;
using WLFramework.DataAccess;
using WLFramework.Json;
using WLFramework.Web;
using WLFramework.Data.Linq;
using GenericHtml;

namespace SampleSite.admin.ajax
{
    /// <summary>
    /// updateUserPosition 的摘要说明
    /// </summary>
    public class updateUserPosition : AjaxHttpHandler
    {
        public class JsonObject
        {
            [Required]
            public int U_ID { get; set; }

            [Required]
            public int P_ID { get; set; }

            [Required]
            public int P_State { get; set; }
        }

        public class InputData
        {
            [Required]
            public string data { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            InputData input;
            var errors = context.GetModel<InputData>(out input);
            if (errors.Count == 0)
            {
                List<JsonObject> list = JSON.Instance.ToObject<List<JsonObject>>(input.data);


                using (PermissionContext db = new PermissionContext())
                {

                    var accessor = DataAccessor.CreateInstance<PermissionCommand>(db);
                    db.BeginTransaction();

                    db.sys_UserPosition.Where(k => k.U_ID == list[0].U_ID)
                        .Delete();

                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i].P_State == 1)
                        {
                            var result = accessor.UpdateUserPosition(
                            list[i].U_ID,
                            list[i].P_ID);

                            if (result.ErrorID != 0)
                                throw new Exception(result.ErrorMsg);
                        }
                    }

                    db.CommitTransaction();
                }

                context.Response.Write(JSON.Instance.ToJSON(JSONResult.Success));
            }
            else
            {
                throw new Exception("输入的数据格式不正确");
            }
        }
    }
}